package com.ruoyi.develop.lvBuy.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.goodsSalebuy.domain.GoodsSalebuy;
import com.ruoyi.develop.goodsSalebuy.service.IGoodsSalebuyService;
import com.ruoyi.develop.goodsSalebuyall.domain.GoodsSalebuyall;
import com.ruoyi.develop.goodsSalebuyall.service.impl.GoodsSalebuyallServiceImpl;
import com.ruoyi.develop.lvDo.domain.LvDo;
import com.ruoyi.develop.lvDo.service.ILvDoService;
import com.ruoyi.develop.orderIronRecord.domain.OrderIronRecord;
import com.ruoyi.develop.orderIronRecord.service.IOrderIronRecordService;
import com.ruoyi.develop.orderIronRecordBuy.domain.OrderIronRecordBuy;
import com.ruoyi.develop.orderIronRecordBuy.service.IOrderIronRecordBuyService;
import com.ruoyi.develop.payApply.domain.PayApply;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.lvBuy.domain.LvBuy;
import com.ruoyi.develop.lvBuy.service.ILvBuyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购单Controller
 * @author qh
 * @date 2024-08-09
 */
@RestController
@RequestMapping("/lvBuy/lvBuy")
public class LvBuyController extends BaseController {
    @Autowired
    private ILvBuyService lvBuyService;
    @Autowired
    private GoodsSalebuyallServiceImpl goodsSalebuyallService;
    @Autowired
    private IGoodsSalebuyService goodsSalebuyService;
    @Autowired
    private IGoodsSaleService iGoodsSaleService;
    @Autowired
    private IOrderIronRecordService orderIronRecordService;
    @Autowired
    private IOrderIronRecordBuyService orderIronRecordBuyService;
    @Autowired
    private ILvDoService lvDoService;
    @Autowired
    private ExportServiceImpl exportService;




    /**
     * 查询采购单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:query')")
    @GetMapping("/list")
    public TableDataInfo list(LvBuy entity) {
        startPage();
        List<LvBuy> list = lvBuyService.selectList(entity);
        return getDataTable(list);
    }


    /**
     * 查询采购单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:query')")
    @GetMapping("/listScope")
    public TableDataInfo listSelf(LvBuy entity) {
        startPage();
        List<LvBuy> list = lvBuyService.listScope(entity);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('develop:LvBuy:query')")
    @GetMapping("/listToMerge")
    public TableDataInfo listWkp(LvBuy entity) {
        startPage();
        List<LvBuy> list = lvBuyService.listToMerge(entity);
        return getDataTable(list);
    }

    /**
     * 导出采购单列表
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:export')")
    @Log(title = "采购单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LvBuy entity) {
        List<LvBuy> list = lvBuyService.selectList(entity);
        ExcelUtil<LvBuy> util = new ExcelUtil<LvBuy>(LvBuy. class);
        util.exportExcel(response, list, "采购单数据");
    }

    /**
     * 获取采购单详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(lvBuyService.selectById(id));
    }

    /**
     * 新增采购单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:add')")
    @Log(title = "采购单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody LvBuy entity) {
        return toAjax(lvBuyService.insert(entity));
    }

    /**
     * 新增铁件采购单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:add')")
    @Log(title = "采购单", businessType = BusinessType.INSERT)
    @PostMapping("/addBuyIron")
    public AjaxResult addBuyIron(@RequestBody LvBuy entity) {
        if(StringUtils.isNotBlank(entity.getIronRecordId())){
            OrderIronRecord orderIronRecord = orderIronRecordService.selectById(entity.getIronRecordId());
            orderIronRecord.setBuyStatus(BusinessConstants.STATUS_YES);
            orderIronRecordService.update(orderIronRecord);
        }
        return toAjax(lvBuyService.insert(entity));
    }

    /**
     * 修改采购单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:edit')")
    @Log(title = "采购单", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody LvBuy entity) {
        return toAjax(lvBuyService.update(entity));
    }

    /**
     * 删除采购单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:remove')")
    @Log(title = "采购单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(lvBuyService.deleteByIds(ids));
    }

    @DeleteMapping("/removeCg/{ids}")
    public AjaxResult removeCg(@PathVariable String[] ids) {
        String id =ids[0];
        List<GoodsSalebuyall> goodsSalebuyalls=goodsSalebuyallService.selectMainId(id);
        for (GoodsSalebuyall goodsSalebuyall:goodsSalebuyalls){
            goodsSalebuyallService.deleteCg(goodsSalebuyall.getId());
        }

        // 如果是 采购单生成的单据
        LvBuy lvBuy = lvBuyService.selectById(id);
        if(StringUtils.isNotBlank(lvBuy.getLvDoId())){
            LvDo lvDo = lvDoService.selectById(lvBuy.getLvDoId());
            lvDo.setGenBuy(BusinessConstants.STATUS_NO);
            lvDoService.update(lvDo);
        }

        // 如果是 铁件采购单
        OrderIronRecordBuy orderIronRecordBuy = new OrderIronRecordBuy();
        orderIronRecordBuy.setBuyId(lvBuy.getId());
        List<OrderIronRecordBuy> orderIronRecordBuyList = orderIronRecordBuyService.selectList(orderIronRecordBuy);
        for (OrderIronRecordBuy ironRecordBuy:orderIronRecordBuyList){
            orderIronRecordBuyService.deleteById(ironRecordBuy.getId());
            OrderIronRecord orderIronRecord = orderIronRecordService.selectById(ironRecordBuy.getIronRecordId());
            orderIronRecord.setBuyMoney(orderIronRecord.getBuyMoney().subtract(lvBuy.getMoney()));
            orderIronRecord.setBuyRemain(orderIronRecord.getBuyRemain().add(lvBuy.getMoney()));
            orderIronRecordService.update(orderIronRecord);
        }

        return toAjax(lvBuyService.deleteByIds(ids));
    }


    /** * 删除铁件的请购单 */
    @DeleteMapping("/removeIronBuy/{ids}")
    public AjaxResult removeIronBuy(@PathVariable String[] ids) {
        for (String buyId:ids){
            LvBuy lvBuy = lvBuyService.selectById(buyId);
            OrderIronRecordBuy params = new OrderIronRecordBuy();
            params.setBuyId(buyId);
            List<OrderIronRecordBuy> orderIronRecordBuys = orderIronRecordBuyService.selectList(params);
            for(OrderIronRecordBuy orderIronRecordBuy:orderIronRecordBuys){
                orderIronRecordBuyService.deleteById(orderIronRecordBuy.getId());
                OrderIronRecord orderIronRecord = orderIronRecordService.selectById(orderIronRecordBuy.getIronRecordId());
                orderIronRecord.setBuyMoney(orderIronRecord.getBuyMoney().subtract(lvBuy.getMoney()));
                orderIronRecord.setBuyRemain(orderIronRecord.getBuyRemain().add(lvBuy.getMoney()));
                orderIronRecordService.update(orderIronRecord);
            }
        }
        return toAjax(lvBuyService.deleteByIds(ids));
    }


    @DeleteMapping("/piliangdaohuo/{ids}")
    public AjaxResult piliangdaohuo(@PathVariable String[] ids) {
        String id =ids[0];

        LvBuy lvBuy = lvBuyService.selectById(id);
        lvBuy.setArrivalStatus(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL);
        List<GoodsSalebuyall> goodsSalebuyalls=goodsSalebuyallService.selectMainId(id);
        for (GoodsSalebuyall goodsSalebuyall:goodsSalebuyalls){
            goodsSalebuyall.setDaohuoStatus(BusinessConstants.GOODS_ARRIVAL_STATUS_ALL);
            goodsSalebuyallService.update(goodsSalebuyall);
            List<GoodsSalebuy> goodsSalebuyList=goodsSalebuyService.selectByCgallId(goodsSalebuyall.getId());
            for(GoodsSalebuy goodsSalebuy:goodsSalebuyList){
                if(StringUtils.isNotBlank(goodsSalebuy.getGoodsSaleId())){
                    GoodsSale goodsSale=iGoodsSaleService.selectById(goodsSalebuy.getGoodsSaleId());
                    if(goodsSale!=null){
                        goodsSale.setStatus(BusinessConstants.SALE_TYPE_10);
                        iGoodsSaleService.update(goodsSale);
                    }
                }
            }
        }
        return toAjax( lvBuyService.update(lvBuy));
    }

    /**
     * 新增 铁件 合并 采购单
     */
    @PreAuthorize("@ss.hasPermi('develop:LvBuy:add')")
    @Log(title = "采购单", businessType = BusinessType.INSERT)
    @PostMapping("/addForIronRecordList")
    public AjaxResult addForIronRecordList(@RequestBody LvBuy entity) {
        List<OrderIronRecordBuy> ironBuyList =  entity.getIronRecordBuyList();
        entity.setPayApplyRemainMoney(entity.getMoney());
        entity.setShengyu(entity.getMoney());
        entity.setFukuan(BigDecimal.ZERO);
        lvBuyService.insert(entity);
        for (OrderIronRecordBuy orderIronRecordBuy:ironBuyList){
            orderIronRecordBuy.setBuyId(entity.getId());
            orderIronRecordBuy.setStatus(BusinessConstants.STATUS_YES);
            orderIronRecordBuyService.update(orderIronRecordBuy);
        }
        return AjaxResult.success();
    }

    @Log(title = "采购列表导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LvBuy entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        List<LvBuy> list = lvBuyService.selectList(entity);
        list.stream().forEach(e -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getCreateTime()));
            e.setParams(map);
            map.put("ywType", DictUtils.getDictLabel("caigou_type", e.getYwType()));
            map.put("source", DictUtils.getDictLabel("buy_source", e.getSource()));
            map.put("payApplyState", DictUtils.getDictLabel("buy_pay_status", e.getPayApplyState()));
            map.put("arrivalStatus", DictUtils.getDictLabel("daohuo_status", e.getArrivalStatus()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if (com.ruoyi.common.utils.StringUtils.isBlank(fileName)) {
            fileName = "采购记录表.xlsx";
        }
        String templateName = "采购记录表.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }




}
